const Province = require("../../dbs/models/province");
const City = require("../../dbs/models/city");
const axios = require("axios");

module.exports = {
  // 定位
  get position() {
    return async ctx => {
      let {
        status,
        data: { province, city, ip }
      } = await axios.get("http://cp-tools.cn/geo/getPosition");
      if (status === 200 && province && city && ip) {
        return (ctx.body = {
          code: 0,
          msg: "获取成功",
          data: {
            province,
            city,
            ip
          }
        });
      } else {
        let ip = ctx.request.ip;
        let {
          status,
          data: {
            code,
            data: { region, city }
          }
        } = await axios.get(
          `http://ip.taobao.com/service/getIpInfo.php?ip=${ip}`
        );
        if (status === 200 && code == 0) {
          return (ctx.body = {
            code: 0,
            msg: "获取成功",
            data: {
              province: region ? region : "",
              city: city ? city : "",
              ip
            }
          });
        } else {
          ctx.throw(400, "定位失败");
        }
      }
    };
  },
  // 所有省份
  get province() {
    return async ctx => {
      let res = await Province.find();
      if (res.length > 0) {
        return (ctx.body = {
          code: 0,
          msg: "获取成功",
          data: res.map(item => {
            return {
              id: item.id,
              name: item.name
            };
          })
        });
      } else {
        ctx.throw(400, "暂无数据");
      }
    };
  },
  // 所有城市
  get city() {
    return async ctx => {
      let res = await City.find();
      if (res.length > 0) {
        let data = [];
        res.forEach(item => {
          item.value.forEach(el => {
            if (el.length > 0) {
              data.push(...el);
            } else {
              data.push(el);
            }
          });
        });
        if (res.length > 0) {
          return (ctx.body = {
            code: 0,
            msg: "获取成功",
            data
          });
        }
      } else {
        ctx.throw(400, "暂无数据");
      }
    };
  },
  // 根据id来获取对应省份下的所有城市
  get Cityid() {
    return async ctx => {
      let { id } = ctx.params;
      if (id) {
        let res = await City.findOne({ id });
        if (res && res.value.length > 0) {
          return (ctx.body = {
            code: 0,
            msg: "获取成功",
            data: res.value
          });
        } else {
          ctx.throw(400, "暂无数据");
        }
      } else {
        ctx.throw(400, "请输入正确参数");
      }
    };
  }
};
